#include "addgoods.h"
#include "ui_addgoods.h"

Addgoods::Addgoods(QWidget *parent,int sid) :
    QDialog(parent),
    ui(new Ui::Addgoods)
{
    ui->setupUi(this);
    myDatabase.getConnection();
    m_sid = sid;
}

Addgoods::~Addgoods()
{
    delete ui;
}

void Addgoods::on_add_clicked()
{
    QString gname = ui->gname->text();
    int num = ui->gnum->text().toInt();
    QSqlQuery sql;
    sql.prepare("SELECT* FROM tb_goodsinstore WHERE sid = :sid AND name = :name");
    sql.bindValue(":sid",m_sid);
    sql.bindValue(":name",gname);
    sql.exec();
    if(sql.first()){
        int num0 = sql.value("num").toInt();
        QSqlQuery sql2;
        sql2.prepare("UPDATE tb_goodsinstore SET num = :totalnum WHERE sid = :sid AND name = :name");
        sql2.bindValue(":sid",m_sid);
        sql2.bindValue(":totalnum",num0+num);
        sql2.bindValue(":name",gname);
        sql2.exec();
        QMessageBox::information(this,"提示","进货成功！",QMessageBox::Yes);

        sql.prepare("SELECT gnum FROM tb_goods WHERE gname = :gname");
        sql.bindValue(":gname",gname);
        sql.exec();
        sql.first();
        num0 = sql.value("gnum").toInt();
        sql.prepare("UPDATE tb_goods SET gnum = :totalnum WHERE gname = :gname");
        sql.bindValue(":gname",gname);
        sql.bindValue(":totalnum",num0+num);
        sql.exec();

        sql.prepare("SELECT gcat FROM tb_goods WHERE gname = :gname");
        sql.bindValue(":gname",gname);
        sql.exec();
        sql.first();
        QString cat = sql.value("gcat").toString();

        sql.prepare("SELECT cnum FROM tb_goods_cat WHERE cname = :cname");
        sql.bindValue(":cname",cat);
        sql.exec();
        sql.first();
        num0 = sql.value("cnum").toInt();
        sql.prepare("UPDATE tb_goods_cat SET cnum = :totalnum WHERE cname = :cname");
        sql.bindValue(":cname",cat);
        sql.bindValue(":totalnum",num0+num);
        sql.exec();
    }
    else{
        QMessageBox::information(this,"提示","没有此商品！",QMessageBox::Yes);
    }
    this->~Addgoods();
}

